import { RouteMapManager } from 'my-ts-core/security';
import { User } from 'my-web-core/auth';
import React from 'react';
import { Route } from 'react-router-dom';

import RouteMapConfig from '@/shared/auth/route-map-config';

const NoPermission = React.lazy(() => import('@/shared/components/NoPermission'));

export function getGuardedRoute(route: string, element: any, currentUser: User | null) {
  // filter((a): a is string => !!a) acts like filter((a): a is string => a !== null && a !== undefined && a !== '')
  const roleAuthorities = currentUser?.fullRoles
    ?.map((r) => r.authority)
    .filter((a): a is string => !!a);
    
  if (!RouteMapManager.checkCanActivateRoute(RouteMapConfig.getRequestMaps(), route, roleAuthorities)) {
    return (
      <Route
        path={route}
        element={
          <React.Suspense>
            <NoPermission />
          </React.Suspense>
        }
      />
    );
  }

  return <Route path={route} element={<React.Suspense>{element}</React.Suspense>} />;
}

export function getGuardedElement(route: string, element: any, currentUser: User | null) {
  // filter((a): a is string => !!a) acts like filter((a): a is string => a !== null && a !== undefined && a !== '')
  const roleAuthorities = currentUser?.fullRoles
    ?.map((r) => r.authority)
    .filter((a): a is string => !!a);

  if (!RouteMapManager.checkCanActivateRoute(RouteMapConfig.getRequestMaps(), route, roleAuthorities)) {
    return (
      <React.Suspense>
        <NoPermission />
      </React.Suspense>
    );

    // Redirect them to the /login page, but save the current location they were
    // trying to go to when they were redirected. This allows us to send them
    // along to that page after they login, which is a nicer user experience
    // than dropping them off on the home page.
    // return <Navigate to="/authentication/login" state={{ from: location }} replace />;
  }

  return <React.Suspense>{element}</React.Suspense>;
}
